/*
 *
 * SimplePCR1000 (Qt4) Version 1.x
 * Copyright (C) 2011  Tyler H. Jones (me@tylerjones.me)
 * http://www.thebasementserver.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


#include "mainwindow.h"
#include "../build/ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle(APP_NAME" "APP_VERSION"- [Radio OFF]");

    //Initialize the timers
    sstimer = new QTimer();
    hangtimer = new QTimer();
    scantimer = new QTimer();

    //Connect to the DB
    DB = new Database();
    DB->Connect();

    //Make the Settings Window
    SETD = new SettingsDialog(this, DB);

    //Initialize private variables
    QuitIntent = false;
    curFreq = "100.0";
    PowerState = false;
    LastDialVal = 0;

    //Set the COM Port
    this->ComPort = SET.get(S_PORT).toString();

    RC.Open(this->ComPort);
    //Connect buttons
    connect(ui->btnPower,SIGNAL(clicked()),this,SLOT(onPower()));
    connect(ui->txtDirectTuning,SIGNAL(returnPressed()),this,SLOT(DirectChangeFreq()));
    //connect(ui->txtDirectTuning,SIGNAL(onClick()),this,SLOT(clicked_txtDirectTuning()));
    //Dials
    connect(ui->dialVolume,SIGNAL(valueChanged(int)),this,SLOT(changeVolume(int)));
    connect(ui->dialSquelch,SIGNAL(valueChanged(int)),this,SLOT(changeSquelch(int)));
    connect(ui->dialTune,SIGNAL(valueChanged(int)),this,SLOT(DialChangeFreq(int)));
    //List views
    connect(ui->cboMode,SIGNAL(currentIndexChanged(QString)),this,SLOT(changeMode(QString)));
    connect(ui->cboFilter,SIGNAL(currentIndexChanged(QString)),this,SLOT(changeFilter(QString)));
    //Menus
    connect(ui->menuFileExit,SIGNAL(triggered()),this,SLOT(clickExit()));
    connect(ui->menuHelpAbout,SIGNAL(triggered()),this,SLOT(showAbout()));
    connect(ui->menuHelpGettingStarted,SIGNAL(triggered()),this,SLOT(showGettingStarted()));
    //connect(ui->menuFileSettings,SIGNAL(triggered()),this,SLOT(showSettings()));
    //Sliders
    connect(ui->sliderIFShift,SIGNAL(valueChanged(int)),this,SLOT(changeIFShift(int)));
    //Timers
    connect(scantimer, SIGNAL(timeout()), this, SLOT(timerScanTick()));
    connect(sstimer, SIGNAL(timeout()), this, SLOT(UpdateSignalMeter()));
    connect(hangtimer, SIGNAL(timeout()), this, SLOT(timerHangTick()));
    //Keypad Buttons
    connect(ui->btnKey0,SIGNAL(clicked()),this,SLOT(pressKey0()));
    connect(ui->btnKey1,SIGNAL(clicked()),this,SLOT(pressKey1()));
    connect(ui->btnKey2,SIGNAL(clicked()),this,SLOT(pressKey2()));
    connect(ui->btnKey3,SIGNAL(clicked()),this,SLOT(pressKey3()));
    connect(ui->btnKey4,SIGNAL(clicked()),this,SLOT(pressKey4()));
    connect(ui->btnKey5,SIGNAL(clicked()),this,SLOT(pressKey5()));
    connect(ui->btnKey6,SIGNAL(clicked()),this,SLOT(pressKey6()));
    connect(ui->btnKey7,SIGNAL(clicked()),this,SLOT(pressKey7()));
    connect(ui->btnKey8,SIGNAL(clicked()),this,SLOT(pressKey8()));
    connect(ui->btnKey9,SIGNAL(clicked()),this,SLOT(pressKey9()));
    connect(ui->btnKeyDec,SIGNAL(clicked()),this,SLOT(pressKeyDec()));
    connect(ui->btnKeyEnt,SIGNAL(clicked()),this,SLOT(pressKeyEnt()));
    //All other buttons
    connect(ui->btnSettings,SIGNAL(clicked()),this,SLOT(clickSettings()));
    connect(ui->btnBackspace,SIGNAL(clicked()),this,SLOT(clickBackspace()));
    connect(ui->btnDelete,SIGNAL(clicked()),this,SLOT(clickDelete()));
    connect(ui->btnHang,SIGNAL(clicked()),this,SLOT(clickHang()));
    connect(ui->btnFreqList,SIGNAL(clicked()),this,SLOT(clickFreqList()));
    connect(ui->btnScrollBack,SIGNAL(clicked()),this,SLOT(clickScrollBack()));
    connect(ui->btnScrollForward,SIGNAL(clicked()),this,SLOT(clickScrollForward()));
    connect(ui->btnHide,SIGNAL(clicked()),this,SLOT(clickHide()));
    connect(ui->btnFreqList,SIGNAL(clicked()),this,SLOT(clickShowChannels()));
    connect(ui->btnLockout,SIGNAL(clicked()),this,SLOT(changeLockout()));
    connect(ui->btnScan,SIGNAL(clicked()),this,SLOT(activateScanner()));
    connect(ui->btnMute,SIGNAL(clicked()),this,SLOT(changeMute()));
    //Checkboxes
    connect(ui->chkAGC,SIGNAL(toggled(bool)),this,SLOT(changeAGC(bool)));
    connect(ui->chkVSC,SIGNAL(toggled(bool)),this,SLOT(changeVSC(bool)));
    connect(ui->chkAtten,SIGNAL(toggled(bool)),this,SLOT(changeAtten(bool)));
    connect(ui->chkNoiseBlanking,SIGNAL(toggled(bool)),this,SLOT(changeAFBlanking(bool)));

    //Populate the list views
    ui->cboFilter->addItems(COM.FilterComboBox);
    ui->cboMode->addItems(COM.ModeComboBox);

    //Make the statusbar
    lblSBLog = new QLabel("  Welcome to SimplePCR1000!    ");
    lblSBPower = new QLabel("  Radio <span style=\"color:red;\"><b>OFF</b></span>  ");
    lblSBPort = new QLabel("  " + this->ComPort + "  ");
    lblSBFreq = new QLabel("<center>" + curFreq + "</center>");
    ui->statusBar->addPermanentWidget(lblSBLog);
    ui->statusBar->addPermanentWidget(lblSBPower);
    ui->statusBar->addPermanentWidget(lblSBPort);
    ui->statusBar->addPermanentWidget(lblSBFreq);

    //Make the system try icon
    createTrayIcon();

    onPower(RC.getPower());
}

void MainWindow::createTrayIcon() {
    //Setand initialize tray icon object
    ti = new QSystemTrayIcon(this);
    ti->setIcon(QIcon(":/simplepcr1000"));
    ti->setToolTip(APP_NAME" - Running");

    //Make actions
    connect(ti, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onTIclick(QSystemTrayIcon::ActivationReason)));

    //
    //Make context menu items
    //
    actExit = new QAction("E&xit",this);
    actExit->setIcon(QIcon(":/x"));
    actExit->setToolTip ("Quit the application");
    connect(actExit,SIGNAL(triggered()),this,SLOT(onQuit()));

    actShow = new QAction("&Show Window",this);
    //actShow->setIcon(QIcon(":/settings"));
    actShow->setToolTip("Show the radio user interface");
    connect(actShow,SIGNAL(triggered()),this,SLOT(onShow()));

    actMute = new QAction("&Mute",this);
    actMute->setCheckable(true);
    actMute->setChecked(SET.get(S_MUTE).toBool());
    //actMute->setIcon(QIcon(SET.get(S_MUTE).toBool()?":/pause":":/play"));
    actMute->setText("&Mute");
    connect(actMute,SIGNAL(triggered()),this,SLOT(changeMute()));

    actScan = new QAction("&Scan",this);
    actScan->setCheckable(true);
    actScan->setChecked(SET.get(S_SCAN).toBool());
    actScan->setIcon(QIcon(SET.get(S_SCAN).toBool()?":/pause":":/play"));
    actScan->setText("&Scan");
    connect(actScan,SIGNAL(triggered()),this,SLOT(activateScanner()));

    actLockout = new QAction("Lockout Channel",this);
    actLockout->setVisible(false);
    actLockout->setText("Lockout Channel");
    connect(actLockout,SIGNAL(triggered()),this,SLOT(changeLockout()));

    actAbout = new QAction("&About",this);
    actAbout->setIcon(QIcon(":/info"));
    actAbout->setToolTip("About "APP_NAME);
    connect(actAbout,SIGNAL(triggered()),this,SLOT(showAbout()));

    actGettingStarted = new QAction("&Getting Started",this);
    actGettingStarted->setIcon(QIcon(":/help2"));
    actGettingStarted->setToolTip("Getting Started With"APP_NAME);
    connect(actGettingStarted,SIGNAL(triggered()),this,SLOT(showGettingStarted()));

    //
    //Create the right-click context menu
    //
    stiMenu = new QMenu(0);
    stiMenu->addAction(actShow);
    stiMenu->addSeparator();
    stiMenu->addAction(actMute);
    stiMenu->addAction(actScan);
    stiMenu->addAction(actLockout);
    stiMenu->addSeparator();
    stiMenu->addAction(actAbout);
    stiMenu->addAction(actGettingStarted);
    stiMenu->addSeparator();
    stiMenu->addAction(actExit);
    ti->setContextMenu(stiMenu);
    ti->show();
}

void MainWindow::ReloadSettings() {
    LoadSettings();
    if(scantimer->isActive()) {
        scantimer->stop();
        scantimer->start(SET.get(S_SCAN_IVAL).toInt());
    }
    QString newport = SET.get(S_PORT).toString().trimmed();
    if(this->ComPort.trimmed() != newport) {
        lblSBPort->setText(newport);
        this->ComPort = newport;
        if(RC.getPower()) { onPower(false); }
        RC.Close();
        RC.Open(this->ComPort);
        if(RC.getPower()) { onPower(true); }
    }
}

void MainWindow::LoadSettings() {
    ui->lcdFreq->display(SET.get(S_FREQ).toDouble());
    lblSBFreq->setText(SET.get(S_FREQ).toString());
    ui->cboFilter->setCurrentIndex(COM.FilterComboBox.indexOf(SET.get(S_FILTER).toString()));
    ui->cboMode->setCurrentIndex(COM.ModeComboBox.indexOf(SET.get(S_MODE).toString()));
    ui->dialSquelch->setValue(SET.get(S_SQU).toInt());
    ui->dialVolume->setValue(SET.get(S_VOL).toInt());
    ui->sliderIFShift->setValue(SET.get(S_IFSHIFT).toInt());
    ui->btnMute->setChecked(SET.get(S_MUTE).toBool());
    ui->btnScan->setChecked(SET.get(S_SCAN).toBool());
    ui->chkAGC->setChecked(SET.get(S_AGC).toBool());
    ui->chkVSC->setChecked(SET.get(S_VSC).toBool());
    ui->chkNoiseBlanking->setChecked(SET.get(S_NB).toBool());
    ui->chkAtten->setChecked(SET.get(S_ATTEN).toBool());
    RC.setFreqModeFilter(SET.get(S_FREQ).toString(), SET.get(S_MODE).toString(), SET.get(S_FILTER).toString());
    RC.setVolume(SET.get(S_VOL).toInt());
    RC.setSquelch(SET.get(S_SQU).toInt());
    RC.setIFShift(SET.get(S_IFSHIFT).toInt());
    RC.setAGC(SET.get(S_AGC).toBool());
    RC.setVSC(SET.get(S_VSC).toBool());
    RC.setNoiseBlanking(SET.get(S_NB).toBool());
    RC.setAtten(SET.get(S_ATTEN).toBool());
    if(SET.get(S_MUTE).toBool()) { RC.setVolume(0); }
}

void MainWindow::SaveSettings() {
    SET.set(S_FREQ,this->curFreq);
    SET.set(S_VOL,QString::number(ui->dialVolume->value()));
    SET.set(S_SQU,QString::number(ui->dialSquelch->value()));
    SET.set(S_IFSHIFT,QString::number(ui->sliderIFShift->value()));
    SET.set(S_MODE,ui->cboMode->currentText());
    SET.set(S_FILTER,ui->cboFilter->currentText());
    SET.set(S_MUTE,ui->btnMute->isChecked());
    SET.set(S_AGC,ui->chkAGC->isChecked());
    SET.set(S_VSC,ui->chkVSC->isChecked());
    SET.set(S_NB,ui->chkNoiseBlanking->isChecked());
    SET.set(S_ATTEN,ui->chkAtten->isChecked());
    SET.set(S_SCAN,ui->btnScan->isChecked());
}

MainWindow::~MainWindow()
{
    SaveSettings();
    RC.Close();
    delete ui;
}

void MainWindow::MsgCallback(int code, QString msg) {

}

void MainWindow::pressKey1() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "1");
}

void MainWindow::pressKey2() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "2");
}

void MainWindow::pressKey3() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "3");
}

void MainWindow::pressKey4() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "4");
}

void MainWindow::pressKey5() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "5");
}

void MainWindow::pressKey6() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "6");
}

void MainWindow::pressKey7() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "7");
}

void MainWindow::pressKey8() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "8");
}

void MainWindow::pressKey9() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "9");
}

void MainWindow::pressKey0() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + "0");
}

void MainWindow::pressKeyDec() {
    ui->txtDirectTuning->setText(ui->txtDirectTuning->text() + ".");
}

void MainWindow::pressKeyEnt() {
    DirectChangeFreq();
}

void MainWindow::clickExit() {
    SaveSettings();
    QuitIntent = true;
    this->close();
}

void MainWindow::clickHide() {
    this->hide();
}

void MainWindow::changeMute() {
    changeMute(!SET.get(S_MUTE).toBool());
}

void MainWindow::changeMute(bool val) {
    SET.set(S_MUTE, val);
    actMute->setChecked(val);
    ui->btnMute->setChecked(val);
    if(val) {
        RC.setVolume(0);
        ui->dialVolume->setValue(0);
        return;
    } else {
        RC.setVolume(SET.get(S_VOL).toInt());
        ui->dialVolume->setValue(SET.get(S_VOL).toInt());
        return;
    }
}

void MainWindow::onTIclick(QSystemTrayIcon::ActivationReason reason) {
    if(reason == QSystemTrayIcon::DoubleClick) { this->show(); }
}

void MainWindow::activateScanner() {
    activateScanner(!SET.get(S_SCAN).toBool());
}

void MainWindow::activateScanner(bool val) {
    if(DB->ChannelCount() < 2) { return; }
    SET.set(S_SCAN, val);
    if(val) {
        scantimer->start(250);
        return;
    } else {
        scantimer->stop();
        return;
    }
    actScan->setChecked(val);
    ui->btnScan->setChecked(val);
}

void MainWindow::clickScrollBack() {
    ui->btnScan->setChecked(false);
    scantimer->stop();

    QString freq = RC.curFreq;
    if(ui->btnScan->isChecked() && DB->CheckChannelExists(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()])) {
        QStringList chans = DB->GetAllChannels();
        int idx = chans.indexOf(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]);
        if(idx == 0) {
            SetChannelFreq(chans.at(chans.count() - 1));
        } else {
            SetChannelFreq(chans.at(idx - 1));
        }
    }

}

void MainWindow::clickScrollForward() {
    ui->btnScan->setChecked(false);
    scantimer->stop();
    QString freq = RC.curFreq;

    if(ui->btnScan->isChecked() && DB->CheckChannelExists(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()])) {
        QStringList chans = DB->GetAllChannels();
        int idx = chans.indexOf(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]);
        if(idx == chans.count() - 1) {
            SetChannelFreq(chans.at(0));
        } else {
            SetChannelFreq(chans.at(idx + 1));
        }
    }
}

void MainWindow::clickAddFreq() {
    QString freq = RC.curFreq;
    DB->AddChannel(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]);
}

void MainWindow::clickSettings() {
    SETD->show();
}

void MainWindow::clickDelete() {
    QString freq = RC.curFreq;

    QStringList chans;
    if(ui->btnScan->isChecked() && DB->CheckChannelExists(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()])) {
        chans.append(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]);
        DB->RemoveChannels(chans);
    }
}

void MainWindow::clickShowChannels() {

}

void MainWindow::clickResetIFShift() {
    ui->sliderIFShift->setValue(127);
    RC.setIFShift(127);
}

void MainWindow::clickBackspace() {
    if(ui->txtDirectTuning->text() == "") { return; }
    QString str = ui->txtDirectTuning->text();
    str.chop(1);
    ui->txtDirectTuning->setText(str);
}

void MainWindow::changeLockout() {
    changeLockout(!DB->GetLockout(RC.curFreq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]));
}

void MainWindow::changeLockout(bool val) {
    if(!SET.get(S_SCAN).toBool() && DB->ChannelCount() < 2) { return; }
    QString freq = RC.curFreq;

    if(DB->CheckChannelExists(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()])) {
        DB->LockoutChannel(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()], val);
        ui->btnLockout->setChecked(val);
        actLockout->setVisible(!val);
    }
}

void MainWindow::changeHangDelay() {
    changeHangDelay(!DB->GetHang(RC.curFreq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()]));
}

void MainWindow::changeHangDelay(bool val) {
    if(!SET.get(S_SCAN).toBool() && DB->ChannelCount() < 2) { return; }
    QString freq = RC.curFreq;

    if(DB->CheckChannelExists(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()])) {
        DB->HangChannel(freq.remove(".") + COM.ModeValues[ui->cboMode->currentText()] + COM.FilterValues[ui->cboFilter->currentText()], val);
        ui->btnHang->setChecked(val);
    }
}

void MainWindow::changeAGC(bool val) {
    RC.setAGC(val);
}

void MainWindow::changeVSC(bool val) {
    RC.setVSC(val);
}

void MainWindow::changeAtten(bool val) {
    RC.setAtten(val);
}

void MainWindow::changeAFBlanking(bool val) {
    RC.setNoiseBlanking(val);
}

void MainWindow::changeIFShift(int val) {
    ui->sliderIFShift->setToolTip("IF Shift Value = " + QString::number(val));
    RC.setIFShift(val);
}

void MainWindow::clicked_txtDirectTuning() {
    if(ui->txtDirectTuning->text().length() > 0) {
        ui->txtDirectTuning->selectAll();
    }
}

void MainWindow::changeVolume(int val) {
    RC.setVolume(val);
}

void MainWindow::changeSquelch(int val) {
    RC.setSquelch(val);
}

void MainWindow::DirectChangeFreq() {
    ui->btnScan->setChecked(false);
    scantimer->stop();
    if(ui->txtDirectTuning->text().trimmed().length() < 1) { ui->txtDirectTuning->setText(""); return; }
    bool isok;
    float test = ui->txtDirectTuning->text().toFloat(&isok);
    if(!isok) { QMessageBox::warning(0, MB_InvalidFreq_T, MB_InvalidFreq_B, QMessageBox::Ok); ui->txtDirectTuning->selectAll(); return; }
    if(RC.setFreqModeFilter(ui->txtDirectTuning->text(), ui->cboMode->currentText(), ui->cboFilter->currentText())) {
        curFreq = RC.curFreq;
        ui->lcdFreq->display(curFreq);
        lblSBFreq->setText(curFreq);
    } else {
        ui->txtDirectTuning->selectAll();
    }
}

void MainWindow::DialChangeFreq(int val) {
    int change;
    double freqc;
    ui->btnScan->setChecked(false);
    scantimer->stop();
    if(val < LastDialVal || (LastDialVal < 11 && val > 90)) {
        change = LastDialVal - val;
        freqc = change * COM.StepSizeValues[ui->cboStepSize->currentText()];
        ui->lcdFreq->display(ui->lcdFreq->value() + freqc);
    } else {
        change = val - LastDialVal;
        freqc = change * COM.StepSizeValues[ui->cboStepSize->currentText()];
        ui->lcdFreq->display(ui->lcdFreq->value() - freqc);
    }
}

void MainWindow::changeMode(QString val) {
    qDebug() << "LOG: changeMode(val) val = " << val;
    if(!RC.setFreqModeFilter(curFreq, val, ui->cboFilter->currentText())) {
        ui->txtDirectTuning->selectAll();
    }
}

void MainWindow::changeFilter(QString val) {
    qDebug() << "LOG: changeFilter(val) val = " << val;
    if(!RC.setFreqModeFilter(curFreq, ui->cboMode->currentText(), val)) {
        ui->txtDirectTuning->selectAll();
    }
}

void MainWindow::SetChannelFreq(QString freqstr) {
    QString freq;
    QString mode;
    QString filter;
    filter = freqstr.right(2);
    freqstr.chop(2);
    mode = freqstr.right(2);
    freq = freqstr.left(10);
    freq.insert(5, ".");
    qDebug() << "DEBUG: SetChannelFreq freqstr = " << freqstr;
    qDebug() << "DEBUG: SetChannelFreq filter = " << filter;
    qDebug() << "DEBUG: SetChannelFreq mode = " << mode;
    qDebug() << "DEBUG: SetChannelFreq freq = " << freq;
    RC.setFreqModeFilter(freq, COM.ModeValues.key(mode), COM.FilterValues.key(filter));
    ui->lcdFreq->display(freq.toDouble());
    ui->cboFilter->setCurrentIndex(COM.FilterComboBox.indexOf(COM.FilterValues.key(filter)));
    ui->cboMode->setCurrentIndex(COM.ModeComboBox.indexOf(COM.ModeValues.key(mode)));
    lblSBFreq->setText(freq);
    curFreq = RC.curFreq;
}

void MainWindow::onPower() {
    onPower(!PowerState);
}

void MainWindow::onPower(bool val) {
    RC.setPower(val);
    PowerState = val;
    QString state = "";
    if(val) { state = "ON"; } else { state = "OFF"; }
    this->setWindowTitle(APP_NAME" "APP_VERSION"- [Radio " + state + "]");
    lblSBPower->setText(val?"  Radio <span style=\"color:green;\"><b>ON</b></span>  ":"  Radio <span style=\"color:red;\"><b>OFF</b></span>  ");
    ui->pbSignal->setValue(0);
    val ? sstimer->start(250) : sstimer->stop();
    if(val) { LoadSettings(); }
    activateScanner(val);
}

// Timer functions
void MainWindow::timerScanTick() {
    qDebug() << "CALL: timerScanTick() called at: " << QTime::currentTime().toString();
}

void MainWindow::timerHangTick() {
    qDebug() << "CALL: timerHangTick() called at: " << QTime::currentTime().toString();
}

void MainWindow::UpdateSignalMeter() {
    bool ok;
    ui->pbSignal->setValue(RC.getSignal().toInt(&ok));
    if(!ok) {
        qDebug() << "pbSignal value could not be converted into INT. QString value = " << RC.getSignal();
        ui->pbSignal->setValue(0);
        return;
    }
}

void MainWindow::ApplyPort() {
    this->ComPort = SET.get(S_PORT).toString();
    SET.set(S_PORT,this->ComPort);
    lblSBPort->setText(this->ComPort);
    RC.Close();
    RC.Open(this->ComPort);
    if(RC.getPower() != PowerState) {
        onPower(RC.getPower());
    }
}

//Show other dialogs
void MainWindow::changeEvent(QEvent *e) {
    //QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::closeEvent(QCloseEvent *e) {
    if(!QuitIntent) {
        e->ignore();
        this->hide();
    }
}

void MainWindow::onShow() {
    this->show();
}

void MainWindow::onQuit() {
    QuitIntent = true;
    this->close();
}

void MainWindow::showSettings() {
    SETD->show();
}

void MainWindow::showAbout() {
    QMessageBox::about(this, tr("About "APP_NAME),
                       tr("<center><b>"APP_NAME" "APP_VERSION" "APP_STABILITY"</b></center><br>"
                            "Author: "APP_DEVELOPER" - (C)2011<br>"
                          "Website: <a href='"APP_WEBSITE"'>"APP_WEBSITE"</a><br>"
                          "Contact: <a href='mailto:"APP_DEV_EMAIL"'>"APP_DEV_EMAIL"</a><br>"));
}

void MainWindow::showGettingStarted() {
    QMessageBox::about(this, tr("About "APP_NAME),
                       tr("<center><b>"APP_NAME" "APP_VERSION" "APP_STABILITY"</b></center><br>"
                            "Author: "APP_DEVELOPER" - (C)2011<br>"
                          "Website: <a href='"APP_WEBSITE"'>"APP_WEBSITE"</a><br>"
                          "Contact: <a href='mailto:"APP_DEV_EMAIL"'>"APP_DEV_EMAIL"</a><br>"));
}

bool MainWindow::AlreadyRunning() {

#if defined(Q_WS_WIN) || defined(Q_WS_PM)

  #ifndef QT_NO_SHAREDMEMORY
    QSharedMemory *sharedMemory = new QSharedMemory(QString(APP_NAME) +
                                                    "SingleApplicationKey",this);
    return !sharedMemory->create(1);
  #else
    return false;
  #endif

#else
    QProcess *pidof = new QProcess();
    QString tmps = "pidof " + qApp->applicationFilePath().split("/", QString::SkipEmptyParts).last();
    pidof->start(tmps);
    if(pidof->waitForStarted() && pidof->waitForFinished()) {
        if(QString(pidof->readAllStandardOutput()).split(" ").count() >= 2) { return true; }
    }
    return false;
#endif
}
